package ws.jonas.sybosc.gui;

import java.awt.BorderLayout;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;

/**
 * TODO: Disable autoscroll when not all down
 * TODO: get output from Common
 */
@SuppressWarnings("serial")
public class LogPanel extends JPanel {
	private static final int MAX_LINES = 1000;
	private static final LogPanel LOGGER = new LogPanel();

	private final SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
	private final JScrollPane scrollPane;
	private final JTextArea textArea;
	private StatusBarPanel statusBar;

	public static LogPanel getInstance() {
		return LOGGER;
	}

	public static void setStatusBar(StatusBarPanel statusBar) {
		LOGGER.setStatusPanel(statusBar);
	}

	private LogPanel() {
		textArea = new JTextArea();
		textArea.setEditable(false);

		scrollPane = new JScrollPane(textArea);
		setLayout(new BorderLayout());
		add(scrollPane, BorderLayout.CENTER);
	}

	public synchronized void println(final String s) {
		println(s, s);
	}

	public synchronized void println(Exception e) {
		final StringBuilder sb = new StringBuilder();
		sb.append(e.toString() + "\n");
		StackTraceElement[] ste = e.getStackTrace();
		for (int i = 0; i < ste.length; ++i) {
			sb.append("\t" + ste[i] + "\n");
		}
		println(sb.toString(), e.getMessage());
	}

	private synchronized void println(final String message, final String statusBarText) {
		SwingUtilities.invokeLater(new Runnable() {
			@Override
			public void run() {
				textArea.append(formatter.format(new Date()) + " " + message + "\n");
				if (textArea.getLineCount() > MAX_LINES + 1) {
					int replaceTo = textArea.getText().indexOf("\n");
					System.out.println("replaceTo = " + replaceTo);
					if (replaceTo != -1) {
						textArea.replaceRange(null, 0, replaceTo + 1);
					}
				}

				if (statusBar != null) {
					statusBar.updateStatusText(statusBarText);
				}
			}
		});
	}

	private void setStatusPanel(StatusBarPanel statusBar) {
		this.statusBar = statusBar;
	}
}
